package com.project.config.interceptor;

import com.project.utils.token.*;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @Description: 登录拦截器
 * @Param:
 * @return:
 * @Author: Mr.Yan
 * @Date: 2018/12/11
 */

@Slf4j
public class SecurityInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws IOException {
        String url = request.getRequestURL().toString();
        String origin = request.getHeader("Origin");
        if(origin == null) {
            origin = request.getHeader("Referer");
        }
        // response.setHeader("Access-Control-Allow-Origin", origin);
        // response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        // response.setHeader("Access-Control-Allow-Credentials", "true");
        // response.setHeader("Access-Control-Max-Age", "3600");
        // response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept,Authorization");

        String serverName = request.getServerName();
        log.info(String.format("请求地址：%s",url));

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return false;
        }
        // 接口方式
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有LoginToken注释，有则跳过认证
        if (method.isAnnotationPresent(LoginToken.class)) {
            LoginToken loginToken = method.getAnnotation(LoginToken.class);
            if (loginToken.required()) {
                return true;
            }
        }

        //检查有没有需要验证token权限的注解
        if (method.isAnnotationPresent(CheckToken.class)) {
            CheckToken checkToken = method.getAnnotation(CheckToken.class);
            if (checkToken.required()) {
                // 执行认证
                if (token == null) {
                    System.out.println("输出结果:————————————————————————" + "无token，请重新登录");
                    throw new CustomException("无身份令牌");
                }

                JwtUtil.parseJWT(token);

                JwtToken jwtToken = new JwtToken(token);
                Subject subject = SecurityUtils.getSubject();
                subject.login(jwtToken);
                return true;
            }else{
                return true;
            }
        }

        return false;
    }
}
